package work.chenxr.security.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import work.chenxr.security.cache.TokenStoreCache;
import work.chenxr.security.service.UserService;
import work.chenxr.security.user.UserDetail;
import work.chenxr.security.utils.TokenUtil;

import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
    private final TokenUtil tokenUtil;
    private final TokenStoreCache tokenStoreCache;
    private final AuthenticationManager authenticationManager;

    @Override
    public Object loginByUsername(String login) {
        JSONObject loginJson = JSON.parseObject(login);

        Authentication authentication;
        try {
            // 用户认证
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginJson.getString("username"), loginJson.getString("password"))
            );
        } catch (Exception e) {
            return "用户名或密码错误";
        }

        // 用户信息
        UserDetail user = (UserDetail) authentication.getPrincipal();

        // 生成 accessToken
        String accessToken = tokenUtil.generator();

        // 保存用户信息到缓存
        tokenStoreCache.saveUser(accessToken, user);

        Map<String, Object> loginVO = new HashMap<>();
        loginVO.put("userId", user.getId());
        loginVO.put("token", accessToken);

        return loginVO;
    }
}
